package jehc.djshi.workflow.web;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.djshi.common.annotation.Auth;
import jehc.djshi.common.base.BaseAction;
import jehc.djshi.common.base.BasePage;
import jehc.djshi.common.base.BaseResult;
import jehc.djshi.common.base.BaseSearch;
import jehc.djshi.common.entity.UserParamInfo;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.workflow.model.LcDeploymentHis;
import jehc.djshi.workflow.service.LcDeploymentHisService;
import jehc.djshi.workflow.util.ActivitiUtil;
import jehc.djshi.workflow.vo.LcTask;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @Desc 历史任务
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Api(value = "历史任务", description = "历史任务",tags = "历史任务")
@RestController
@RequestMapping("/lcTaskHis")
@Slf4j
public class LcTaskHisController extends BaseAction {

    @Resource
    ActivitiUtil activitiUtil;

    @Resource
    private LcDeploymentHisService lcDeploymentHisService;

    /**
     * 查询并分页
     * @param baseSearch
     * @return
     */
    @ApiOperation(value="查询并分页", notes="查询并分页")
    @PostMapping(value="/list")
    @Auth(value = "/lcTaskHis/list",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BasePage<List<LcTask>> getLcApprovalListByCondition(@RequestBody BaseSearch baseSearch){
        Map<String, Object> condition = baseSearch.convert();
        int start = baseSearch.getStart();
        int pageSize = baseSearch.getPageSize();
        HistoricTaskInstanceQuery historicTaskInstanceQuery = activitiUtil.getHistoryService().createHistoricTaskInstanceQuery(); // 创建历史任务实例查询条件
        Object assignee = condition.get("assignee");
        Object owner = condition.get("owner");
        Object candidateUsers = condition.get("candidateUsers");
        Object candidateGroups = condition.get("candidateGroups");
        Object taskName =  condition.get("taskName");
        Object tenantId = condition.get("tenantId");//租户
        if(null != taskName){
            historicTaskInstanceQuery.taskNameLike(String.valueOf(taskName));
        }
        if(null != owner){
            historicTaskInstanceQuery.taskOwner(String.valueOf(owner)); //指定发起人
        }
        if(null != assignee){
            historicTaskInstanceQuery.taskAssignee(String.valueOf(assignee)); //指定经办人
        }
        if(null != candidateUsers){
            historicTaskInstanceQuery.taskCandidateUser(String.valueOf(candidateUsers));//候选人
        }
        if(null != candidateGroups){
            historicTaskInstanceQuery.taskCandidateGroup(String.valueOf(candidateGroups));//组
        }
        if(null != tenantId){
            historicTaskInstanceQuery.taskTenantId(String.valueOf(tenantId));
        }
        historicTaskInstanceQuery.finished();
        historicTaskInstanceQuery.orderByHistoricTaskInstanceEndTime().desc();
        historicTaskInstanceQuery.orderByTaskCreateTime().desc();
        List<HistoricTaskInstance> historicTaskInstances = historicTaskInstanceQuery // 创建历史任务实例查询
                .listPage(start,pageSize);
        long totalCount =historicTaskInstanceQuery.count();

        List<LcTask> lcTasks = new ArrayList<>();
        for(HistoricTaskInstance historicTaskInstance:historicTaskInstances){
            LcTask lcTask = new LcTask();
            lcTask.setName(historicTaskInstance.getName());
            lcTask.setTaskId(historicTaskInstance.getId());
            lcTask.setCategory(historicTaskInstance.getCategory());
            lcTask.setParentTaskId(historicTaskInstance.getParentTaskId());
            lcTask.setPriority(historicTaskInstance.getPriority());
            lcTask.setProcessDefinitionId(historicTaskInstance.getProcessDefinitionId());
            lcTask.setProcessInstanceId(historicTaskInstance.getProcessInstanceId());
            lcTask.setTaskDefinitionKey(historicTaskInstance.getTaskDefinitionKey());
            ProcessDefinition processDefinition = activitiUtil.getProcessDefinitionByInstanceId(historicTaskInstance.getProcessInstanceId());
            if(null != processDefinition){
                Map<String,Object> map = new HashMap<>();
                map.put("deploymentId",processDefinition.getDeploymentId());
                LcDeploymentHis lcDeploymentHis = lcDeploymentHisService.getLcDeploymentHisUnique(map);
                if(null != lcDeploymentHis){
                    lcTask.setProductName(lcDeploymentHis.getProductName());
                    lcTask.setGroupName(lcDeploymentHis.getGroupName());
                    lcTask.setProcessTitle(lcDeploymentHis.getTitle());
                    lcTask.setVersion(lcDeploymentHis.getVersion());
                }
            }

            lcTask.setTenantId(historicTaskInstance.getTenantId());
            lcTask.setCreateTime(historicTaskInstance.getCreateTime());
            lcTask.setStartTime(historicTaskInstance.getStartTime());
            lcTask.setDueDate(historicTaskInstance.getDueDate());
            lcTask.setProcessVariables(historicTaskInstance.getProcessVariables());
            lcTask.setDescription(historicTaskInstance.getDescription());
            lcTask.setExecutionId(historicTaskInstance.getExecutionId());
            lcTask.setFormKey(historicTaskInstance.getFormKey());
            lcTask.setEndTime(historicTaskInstance.getEndTime());
            lcTask.setWorkTimeInMillis(historicTaskInstance.getWorkTimeInMillis());
            lcTask.setDurationInMillis(historicTaskInstance.getDurationInMillis());
            if(!StringUtil.isEmpty(historicTaskInstance.getOwner())){
                UserParamInfo userParamInfo = new UserParamInfo(historicTaskInstance.getOwner());
                userParamInfo = infoList(userParamInfo);
                if(CollectionUtil.isNotEmpty(userParamInfo.getUserinfoEntities())){
                    lcTask.setOwner(userParamInfo.getUserinfoEntities().get(0).getName());
                }else{
                    lcTask.setOwner(historicTaskInstance.getOwner());
                }
            }else{
                lcTask.setOwner("X");
            }
            if(!StringUtil.isEmpty(historicTaskInstance.getAssignee())){
                UserParamInfo userParamInfo = new UserParamInfo(historicTaskInstance.getAssignee());
                userParamInfo = infoList(userParamInfo);
                if(CollectionUtil.isNotEmpty(userParamInfo.getUserinfoEntities())){
                    lcTask.setAssignee(userParamInfo.getUserinfoEntities().get(0).getName());
                }else{
                    lcTask.setAssignee(historicTaskInstance.getAssignee());
                }
            }else{
                lcTask.setAssignee("X");
            }
            lcTasks.add(lcTask);
        }
        return new BasePage(start,pageSize,pageSize,totalCount,lcTasks,true);
    }

    /**
     * 查询单条记录
     * @param taskId
     */
    @ApiOperation(value="查询单条记录", notes="查询单条记录")
    @GetMapping(value="/get/{taskId}")
    @Auth(value = "/lcTaskHis/get",authenticationType = Auth.AuthorizationType.REQUIRED_LOGIN_NOT_AUTH)
    public BaseResult<LcTask> getTask(@PathVariable("taskId")String taskId){
        HistoricTaskInstance historicTaskInstance = activitiUtil.getTaskById(taskId);
        LcTask lcTask = new LcTask();
        lcTask.setName(historicTaskInstance.getName());
        lcTask.setTaskId(historicTaskInstance.getId());
        lcTask.setCategory(historicTaskInstance.getCategory());
        lcTask.setParentTaskId(historicTaskInstance.getParentTaskId());
        lcTask.setPriority(historicTaskInstance.getPriority());
        lcTask.setProcessDefinitionId(historicTaskInstance.getProcessDefinitionId());
        lcTask.setProcessInstanceId(historicTaskInstance.getProcessInstanceId());
        lcTask.setTaskDefinitionKey(historicTaskInstance.getTaskDefinitionKey());
        ProcessDefinition processDefinition = activitiUtil.getProcessDefinitionByInstanceId(historicTaskInstance.getProcessInstanceId());
        if(null != processDefinition){
            Map<String,Object> map = new HashMap<>();
            map.put("deploymentId",processDefinition.getDeploymentId());
            LcDeploymentHis lcDeploymentHis = lcDeploymentHisService.getLcDeploymentHisUnique(map);
            if(null != lcDeploymentHis){
                lcTask.setProductName(lcDeploymentHis.getProductName());
                lcTask.setGroupName(lcDeploymentHis.getGroupName());
                lcTask.setProcessTitle(lcDeploymentHis.getTitle());
                lcTask.setVersion(lcDeploymentHis.getVersion());
            }
        }

        lcTask.setTenantId(historicTaskInstance.getTenantId());
        lcTask.setCreateTime(historicTaskInstance.getCreateTime());
        lcTask.setStartTime(historicTaskInstance.getStartTime());
        lcTask.setDueDate(historicTaskInstance.getDueDate());
        lcTask.setProcessVariables(historicTaskInstance.getProcessVariables());
        lcTask.setDescription(historicTaskInstance.getDescription());
        lcTask.setExecutionId(historicTaskInstance.getExecutionId());
        lcTask.setFormKey(historicTaskInstance.getFormKey());
        lcTask.setEndTime(historicTaskInstance.getEndTime());
        lcTask.setWorkTimeInMillis(historicTaskInstance.getWorkTimeInMillis());
        lcTask.setDurationInMillis(historicTaskInstance.getDurationInMillis());
        if(!StringUtil.isEmpty(historicTaskInstance.getOwner())){
            UserParamInfo userParamInfo = new UserParamInfo(historicTaskInstance.getOwner());
            userParamInfo = infoList(userParamInfo);
            if(CollectionUtil.isNotEmpty(userParamInfo.getUserinfoEntities())){
                lcTask.setOwner(userParamInfo.getUserinfoEntities().get(0).getName());
            }else{
                lcTask.setOwner(historicTaskInstance.getOwner());
            }
        }else{
            lcTask.setOwner("X");
        }
        if(!StringUtil.isEmpty(historicTaskInstance.getAssignee())){
            UserParamInfo userParamInfo = new UserParamInfo(historicTaskInstance.getAssignee());
            userParamInfo = infoList(userParamInfo);
            if(CollectionUtil.isNotEmpty(userParamInfo.getUserinfoEntities())){
                lcTask.setAssignee(userParamInfo.getUserinfoEntities().get(0).getName());
            }else{
                lcTask.setAssignee(historicTaskInstance.getAssignee());
            }
        }else{
            lcTask.setAssignee("X");
        }
        return outDataStr(lcTask);
    }
}
